; (function (window) {
    //操作的角色
    let role = {
        name: '码农',
        x: 19,
        y: 19
    }
    //全局状态变量
    let globalVars = {
        /**分数 */
        score: 0,
        /**渲染界面水平单元个数 */
        viewWidh: 40,
        /**渲染界面垂直单元个数 */
        viewHeight: 20,
        /**背景单元内容 */
        bgUnit: '一',
        gameTitle: '码农躲BUG',
        enemyRate: 1.1,//敌人出现概率
        mainTimer: null,
        enemyTimer: null,
        rateTimer: null,
        dieTrigger:false//触发死亡
    }
    //敌人列表
    let enemyList = [];

    let Enemy = function (x, y, speed) {
        this.x = x || 0;
        this.y = y || 0;
        this.speed = speed || 1;
    }
    Enemy.graph = '车';//敌人的图形元素

    //绘制帧图
    let drawFrame = function () {
        let frameString = "";
        for (let hIndex = 0; hIndex < globalVars.viewHeight; hIndex++) {//列
            for (let wIndex = 0; wIndex < globalVars.viewWidh; wIndex++) {//行
                let unit = globalVars.bgUnit;

                enemyList.forEach(enemy => {
                    let x = Math.floor(enemy.x); //2.1 => 2
                    let y = Math.floor(enemy.y);
                    //length-1是因为名称本身已经占用了一个单位
                    let cond1 = x <= wIndex && x + (Enemy.graph.length-1) >= wIndex && y === hIndex;//敌人在当前坐标位置
                    let cond2 = y === (globalVars.viewHeight - 1);//敌人在最后一行

                    //角色名字左侧或者右侧在敌人名字范围内
                    let cond3 = (x <= role.x && x + (Enemy.graph.length-1) >= role.x)
                        || (x <= role.x + (role.name.length-1) && x + (Enemy.graph.length-1) >= role.x + (role.name.length-1));
                    //绘制敌人
                    if (cond1) {
                        //角色在最后一行和敌人碰撞，就挂了
                        if (cond2 && cond3) {
                            die();
                        }
                        let cond4 = wIndex >= x && wIndex <= x + (Enemy.graph.length-1);//x坐标在敌人名字所在范围
                        if (cond4) {
                            unit = Enemy.graph[wIndex - x];
                        }
                    }
                });

                //最后一行,绘制角色
                if (hIndex === globalVars.viewHeight - 1) {
                    //绘制角色名
                    if (wIndex >= role.x && wIndex <= role.x + (role.name.length-1)) {
                        unit = role.name[wIndex - role.x];
                    }
                }
                frameString += unit;
            }
            frameString += "\n";
        }
        frameString += "《" + globalVars.gameTitle + "》得分：" + globalVars.score;
        frameString += "\n";
        return frameString;
    }
    /**
     * 左移动
     */
    function moveRoleToLeft() {
        role.x -= 1;
        let min = 0;
        if (role.x < min) {
            role.x = min;
        }
    }
    /**
     * 右移动
     */
    function moveRoleToRight() {
        role.x += 1;
        let max = globalVars.viewWidh - (role.name.length-1);
        if (role.x > max) {
            role.x = max;
        }
    }

    let registerEvents = function () {
        window.onkeydown = function (e) {
            let KeyLeftArrowCode = 37;
            let KeyRightArrowCode = 39;
            let KeyACode = 65;
            let KeyDCode = 68;
            if (e.keyCode === KeyLeftArrowCode || e.keyCode === KeyACode) {
                moveRoleToLeft();
            }
            if (e.keyCode === KeyRightArrowCode || e.keyCode === KeyDCode) {
                moveRoleToRight();
            }
        }
    }

    let die = function () {
        clearInterval(globalVars.enemyTimer);
        clearInterval(globalVars.rateTimer);
        clearInterval(globalVars.mainTimer);
        setTimeout(() => {
            console.log("游戏结束，您的得分：" + globalVars.score);
        }, 300);
    }

    let playGame = function () {
        //创建敌人定时器
        globalVars.enemyTimer = setInterval(function () {
            let createCount = Math.floor(Math.random() * 5 * globalVars.enemyRate);
            for (let i = 0; i < createCount; i++) {
                let enemy = new Enemy(Math.floor(Math.random() * globalVars.viewWidh), 0, Math.random() * globalVars.enemyRate);
                enemyList.push(enemy);
            }
        }, 1000);
        //绘制帧定时器
        let count = 0;
        globalVars.mainTimer = setInterval(function () {
            enemyList.forEach(function (enemy, i) {
                enemy.y += enemy.speed;
                //超出显示范围就剔除，并加分
                if (enemy.y >= globalVars.viewHeight + 1) {
                    enemyList.splice(i, 1);
                    globalVars.score++;
                }
            });
            //不能每次绘制就清除，效果不好，会闪屏
            //console.clear();
            console.log(drawFrame())
            count++;
            if (count > 100) {
                console.clear()
                count = 0;
            }
        }, 100)
        //提升难度定时器
        globalVars.rateTimer = setInterval(function () {
            globalVars.enemyRate += 0.1;
        }, 3000)
    }

    let start = function () {
        if (!window.console) {
            window.console = {
                log: function () { }
            };
            alert("your browser not supported window.console");
            return;
        }

        globalVars.enemyRate = 1.1;
        enemyList = [];
        globalVars.score = 0;
        globalVars.viewWidh = 40;
        globalVars.viewHeight = 20;
        role.x = 19;
        Enemy.graph=['BU','G '];

        console.log("%c请先用鼠标点击一下网页页面，游戏需要捕捉网页上的键盘事件（你应该懂吧）！", "font-size:16px;color:#ff6700;")
        console.log("使用键盘左右键或ad字母键移动最下方的码农，躲开所有的汽车，汽车数量和速度会一直增加，看看谁坚持的最久吧！")
        registerEvents();
        let countdown = 6;
        setTimeout(function () {
            if (countdown-- <= 1) {
                playGame();
            } else {
                console.log(countdown);
                //自己调用自己 
                setTimeout(arguments.callee, 1000);
            }
        }, 1000)
        return ("倒计时！");
    }
    console.log("输入 start(); 后即可开始《" + globalVars.gameTitle + "》游戏！");
    window.start = start;
})(window)